<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/12
 * Time: 10:49
 */
class model_baidu
{
    function checkPictureToCheckFace($image_path, $access_token='') {
        if(empty($access_token)){
            $access_token = $this->checkAccessToken();
        }
        $url = 'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=' . $access_token;
        $param = array(
            'image' => $this->base64EncodeImage($image_path),
            'image_type' => 'BASE64',
            'face_field' => 'quality'
        );
        $param = json_encode($param);
        $result = $this->execCurl($url, $param);
        if($result['result'] == false) return $result;
        $data = json_decode($result['data'], true);
        if($data['error_code'] != 0) return array('result' => false, 'err_msg' => '上传的人脸不符合要求，请重新上传五官清晰的真实头像');
        $err_result = array('result' => false, 'err_msg' => '上传的人脸不符合要求，请重新上传五官清晰的真实头像!');
        $quality = $data['result']['face_list'][0]['quality'];
        if($quality['occlusion']['left_eye'] > 0.6) return $err_result; // 左眼被遮挡的阈值
        if($quality['occlusion']['right_eye'] > 0.6) return $err_result; // 右眼被遮挡的阈值
        if($quality['occlusion']['nose'] > 0.7) return $err_result; // 鼻子被遮挡的阈值
        if($quality['occlusion']['mouth'] > 0.7) return $err_result; // 嘴巴被遮挡的阈值
        if($quality['occlusion']['left_cheek'] > 0.8) return $err_result; // 左脸颊被遮挡的阈值
        if($quality['occlusion']['right_cheek'] > 0.8) return $err_result; // 右脸颊被遮挡的阈值
        if($quality['occlusion']['chin_contour'] > 0.6) return $err_result; // 下巴被遮挡阈值
        if($quality['blur'] != 0 && $quality['blur'] > 0.7) return $err_result; // 模糊度范围 0是最清晰，1是最模糊
        if($quality['illumination'] < 40) return $err_result; // 光照范围
        if($quality['completeness'] == 0) return $err_result; // 人脸完整度 0为人脸溢出图像边界，1为人脸都在图像边界内
        return array('result' => true);
    }

    function execCurl($url, $param) {
        if (empty($url) || empty($param)) {
            return array('result' => false, 'err_msg' => 'url or param is null');
        }
        $curl = curl_init();//初始化curl
        curl_setopt($curl, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        $data = curl_exec($curl);//运行curl
        $curl_err_msg = curl_error($curl);
        curl_close($curl);
        if($data === false) {
            return array('result' => false, 'err_msg' => $curl_err_msg);
        }else {
            return array('result' => true, 'data' => $data);
        }
    }

    function base64EncodeImage($image_path) {
        $base64_image = '';
        $image_info = getimagesize($image_path);
        $image_data = fread(fopen($image_path, 'r'), filesize($image_path));
        $base64_image = chunk_split(base64_encode($image_data));
        return $base64_image;
    }

    function checkAccessToken(){
        //我的百度人脸接口，次数有限制
        $condition = array(
          'appid' => 17232303
        );
        $account = pdo_get('tp_baidu_account', $condition);
        if($account){
            $appid = $account['appid'];
            $apikey = $account['apikey'];
            $secretkey = $account['secretkey'];
            if(!$appid || !$apikey || !$secretkey){
                return error(-1, "参数错误");
            }
            $condition = array(
                'appid' => $appid,
                'apikey' => $apikey,
                'secretkey' => $secretkey,
            );
            $access_token_set = pdo_get('tp_baidu_accesstoken', $condition);
            if($access_token_set){
                if($access_token_set['accessexpires'] > time()){
                    return $access_token_set['accesstoken'];
                }else{
                    $url = 'https://aip.baidubce.com/oauth/2.0/token';
                    $post_data['grant_type']  = 'client_credentials';
                    $post_data['client_id'] = $apikey; //'你的 Api Key';
                    $post_data['client_secret'] = $secretkey; //'你的 Secret Key';
                    $o = "";
                    foreach ( $post_data as $k => $v )
                    {
                        $o.= "$k=" . urlencode( $v ). "&" ;
                    }
                    $post_data = substr($o,0,-1);

                    $res = $this->request_post($url, $post_data);
                    // pdo_insert('tp_log', array('text'=>$res)); //记录日志
                    $jsoninfo = json_decode($res, true);
                    $data['appid'] = $appid;
                    $data['apikey'] = $apikey;
                    $data['secretkey'] = $secretkey;
                    $data['accesstoken'] = $jsoninfo['access_token'];
                    $data['accessexpires'] = $jsoninfo['expires_in']+time();
                    $data['remark'] = '重新获取';
                    $res = pdo_insert('tp_baidu_accesstoken', $data);
                    return $jsoninfo['access_token'];
                }
            }else{
                $url = 'https://aip.baidubce.com/oauth/2.0/token';
                $post_data['grant_type']  = 'client_credentials';
                $post_data['client_id'] = $apikey; //'你的 Api Key';
                $post_data['client_secret'] = $secretkey; //'你的 Secret Key';
                $o = "";
                foreach ( $post_data as $k => $v )
                {
                    $o.= "$k=" . urlencode( $v ). "&" ;
                }
                $post_data = substr($o,0,-1);

                $res = $this->request_post($url, $post_data);
                // pdo_insert('tp_log', array('text'=>$res)); //记录日志
                $jsoninfo = json_decode($res, true);
                $data['appid'] = $appid;
                $data['apikey'] = $apikey;
                $data['secretkey'] = $secretkey;
                $data['accesstoken'] = $jsoninfo['access_token'];
                $data['accessexpires'] = $jsoninfo['expires_in']+time();
                $data['remark'] = '新加';
                $res = pdo_insert('tp_baidu_accesstoken', $data);
                return $jsoninfo['access_token'];
            }
        }
    }

    function request_post($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        $curl = curl_init();//初始化curl
        curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($curl);//运行curl
        curl_close($curl);

        return $data;
    }
}